import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login/index.vue'
import home from '@/views/home/home.vue'
import company from '@/views/home/company/company.vue'
import question from '@/views/home/question/question.vue'
import find from '@/views/home/find/find.vue'
import my from '@/views/home/my/my.vue'
import { getLocal } from '@/utils/local'
import { apiGetUserInfo } from '@/api/login'
import store from '@/store/index.js'
import info from '@/views/info/info.vue'
import { Toast } from 'vant'
import editInfo from '@/views/info/editInfo.vue'
import upload from '@/views/info/upload.vue'
import sharemore from '@/views/faceshare/sharemore.vue'
import sharesearch from '@/views/faceshare/sharesearch.vue'
import sharedetail from '@/views/faceshare/sharedetail.vue'
import interview from '@/views/home/question/interview.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: login },
  {
    path: '/home',
    component: home,
    children: [
      { path: '/company', component: company },
      {
        path: '/question',
        component: question,
        meta: {
          needLogin: true
          // _direct: '/question'
        }
      },
      {
        path: '/find',
        component: find
      },
      {
        path: '/my',
        component: my,
        meta: {
          needLogin: true
        }
      }
    ]
  },
  {
    path: '/info',
    component: info,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/editInfo',
    component: editInfo,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/upload',
    component: upload,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/sharemore',
    component: sharemore
  },
  {
    path: '/sharesearch',
    component: sharesearch
  },
  {
    path: '/sharedetail/:id',
    component: sharedetail
  },
  {
    path: '/interview',
    component: interview
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach(async (to, from, next) => {
  // 路由进入前处理
  if (!to.meta.needLogin) {
    next()
  } else {
    const token = getLocal('token')
    if (!token) {
      Toast.fail('您还没有登录哦')
      // if (to.meta._direct) {
      //   router.push(`/login?_dire=${to.meta._direct}`)
      // } else {
      //   router.push('/login')
      // }
      router.push('/login?_redirect=' + to.fullPath)
    } else {
      const userInfo = store.state.userInfo
      if (userInfo) {
        next()
      } else {
        const res = await apiGetUserInfo(token)
        console.log(res)
        res.data.avatar = 'http://localhost:1337' + res.data.avatar
        store.commit('setUserInfo', res.data)
        next()
      }
    }
  }
})

router.afterEach((to, from) => {
  // 路由进入后的处理
  // console.log(to)
  // console.log(from)
  // 修改网页的标题信息
  // 在路由配置里写好 路由元 meta meta是一个对象模型{title:xxx}
  //
})

export default router
